package com.liming.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liming.server.domain.Chapter;
import com.liming.server.domain.ChapterExample;
import com.liming.server.dto.ChapterDto;
import com.liming.server.dto.ChapterPageDto;
import com.liming.server.mapper.ChapterMapper;
import com.liming.server.util.CopyUtil;
import com.liming.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChapterService {
    @Resource
    private ChapterMapper chapterMapper;

    public void list(ChapterPageDto chapterPageDto){
        PageHelper.startPage(chapterPageDto.getPage(),chapterPageDto.getSize());
        ChapterExample chapterExample = new ChapterExample();

        ChapterExample.Criteria criteria = chapterExample.createCriteria();
        if(!StringUtils.isEmpty(chapterPageDto.getCourseId())){
            criteria.andCourseIdEqualTo(chapterPageDto.getCourseId());
        }

        List<Chapter> chapterList = chapterMapper.selectByExample(chapterExample);
        PageInfo<Chapter> pageInfo = new PageInfo<>(chapterList);
        chapterPageDto.setTotal(pageInfo.getTotal());
        //将chapterList通过CopyUtil.copyList()方法复制给chapterDtoList
        List<ChapterDto> chapterDtoList =CopyUtil.copyList(chapterList,ChapterDto.class);
        chapterPageDto.setList(chapterDtoList);
    }
    public void save(ChapterDto chapterDto){
        //将chapterDto通过CopyUtil.copy()方法复制给Chapter
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if(StringUtils.isEmpty(chapterDto.getId())){
            this.insert(chapter);
        }else{
            this.update(chapter);
        }
    }
    private void insert(Chapter chapter){
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }
    private void update(Chapter chapter){
        chapterMapper.updateByPrimaryKey(chapter);
    }
    public void delete(String id){
        chapterMapper.deleteByPrimaryKey(id);
    }

    /**
     * 查找某一课程下的所有章
     * @param courseId
     * @return
     */
    public List<ChapterDto> listByCourse(String courseId) {
        ChapterExample example = new ChapterExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<Chapter> chapterList = chapterMapper.selectByExample(example);
        List<ChapterDto> chapterDtoList = CopyUtil.copyList(chapterList, ChapterDto.class);
        return chapterDtoList;
    }
}
